import hashlib
import json
import os
import uuid
import shutil
import yaml

STORE_DB = 'data/db'
STORE_DIR = 'data/store'
STORE_FONTS = f'{STORE_DIR}/fonts/'

config = {}
if os.path.exists('app.yml'):
    with open('app.yml', encoding='UTF-8') as f:
        config = yaml.safe_load(f)
        # print('load config: ', config)


def mkdirs(path):
    if not os.path.exists(path):
        print("mkdirs: path=" + path)
        os.makedirs(path)
    return path


def init_fonts(path):
    if not os.path.exists(STORE_FONTS):
        print("copy resource: path=" + path)
        shutil.copytree('resource', path, dirs_exist_ok=True)
    return path


def init_path():
    mkdirs(STORE_DB)
    mkdirs(STORE_DIR)
    init_fonts(STORE_DIR)


def init(path=init_path()):
    ### 确保多次调用，只执行一次实际初始化
    ...


init()


def md5(param: str, len=32) -> str:
    if isinstance(param, dict):
        param = json.dumps(param)
    if isinstance(param, str):
        param = param.encode()
    return hashlib.md5(param).hexdigest()[0:len]


def code(len=16) -> str:
    return md5(str(uuid.uuid4()), len)


def indocker():
    return os.environ.get('FASTPOSTER_IN_DOCKER', None) is not None


def inpublic():
    # return True
    return os.environ.get('FASTPOSTER_PROFILE', 'dev') == 'public'